<?php

namespace app\common\component;

use OSS\OssClient;

class OssClients
{

    const HOST = 'http://oss-cn-zhangjiakou.aliyuncs.com';

    protected $bucket = 'meigm-static';

    protected $ossClient;

    protected function __construct()
    {
        $config = config('app')['aliyun_oss'];
        $this->ossClient = new OssClient($config['id'], $config['key'], self::HOST, false);
    }

    /**
     * @return self
     */
    public static function instance()
    {
        static $_instance = [];
        if (empty($_instance)) {
            $_instance = new self();
        }
        return $_instance;
    }

    public function setBucket($bucket)
    {
        $this->bucket = $bucket;
    }

    public function createBucket($bucket)
    {
        $options = [
            OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_STANDARD
        ];
        $exist = $this->ossClient->doesBucketExist($bucket);
        if ($exist !== true) {
            $this->ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ, $options);
        }
        $this->bucket = $bucket;
        return $bucket;
    }

    /**
     * 上传文件  （还是先上传到服务器，然后再上传到oss）
     * @param string $file 本地文件地址
     * @param bool $delLocalFile 上传完成删除本地文件
     * @return array
     */
    public function uploadFile($file, $platformId = '', $delLocalFile = true, $ext = '')
    {
        if (!$ext) {
            $ext = explode('.', $file);
            $ext = end($ext);
        }
        $date = date('Ymd');
        $object = $date . '/' . date('YmdHis') . '_' . rand(1000, 9000) . '.' . $ext;
        if ($platformId) {
            $object = $platformId . '/' . $object;
        }
        if (!file_exists($file))
            return ['error' => 1, 'msg' => '文件不存在'];
        try {
            $result = $this->ossClient->uploadFile($this->bucket, $object, $file);
        } catch (\Exception $e) {
            return ['error' => 1, 'msg' => $e->getMessage()];
        }
        if ($delLocalFile) {
            unlink($file);
        }
        return ['error' => 0, 'data' => $result['info']['url'], 'message' => 'SUCCESS'];
    }

    /**
     * 获取文件签名的url
     * @param string $object
     * @param bool $showSy 水印
     */
    public function getSignUrl($object, $showSy = false)
    {
        if (empty($object) || strpos($object, $this->bucket) == false)
            return $object;
        $arr = explode('?', $object);
        $object = $arr['0'];
        $host = self::HOST;
        if (strpos($object, 'https') !== false) {
            $host = str_replace('http', 'https', $host);
        }
        $url = str_replace('//', '//' . $this->bucket . '.', $host);
        $file = str_replace($url, '', $object);
        $sy = base64_encode('sy/jiayun.png?x-oss-process=image/resize,P_15/rotate,340');
        $options = ['x-oss-process' => 'image/watermark,t_20,g_ne,image_' . $sy
            . '/watermark,t_20,g_nw,image_' . $sy
            . '/watermark,t_20,g_north,image_' . $sy
            . '/watermark,t_20,g_center,image_' . $sy
            . '/watermark,t_20,g_sw,image_' . $sy
            . '/watermark,t_20,g_se,image_' . $sy
        ];
        $path = explode('/', $object);
        $time = substr(end($path), 0, 8);
        if ($time < '20190226') {
            $showSy = false;
        }
        return $this->ossClient->signUrl($this->bucket, ltrim($file, '/'), 60, 'GET', $showSy ? $options : NULL);
    }
}

